﻿using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace ECM7.NantContrib.Functions
{
	[FunctionSet("ecm7-aspnet", "ECM7")]
	public class AspNetFunctions : FunctionSetBase
	{
		public AspNetFunctions(Project project, PropertyDictionary properties)
			: base(project, properties)
		{
		}

		[Function("generate-validation-key")]
		public static string GenerateValidationKeyFunc()
		{
			return CreateKey(64);
		}

		[Function("generate-decryption-key")]
		public static string GenerateDecryptionKeyFunc()
		{
			return CreateKey(32);
		}

		#region private

		private static string CreateKey(int numBytes)
		{
			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
			byte[] buff = new byte[numBytes];

			rng.GetBytes(buff);
			return BytesToHexString(buff);
		}

		private static string BytesToHexString(IEnumerable<byte> bytes)
		{
			StringBuilder hexString = new StringBuilder(64);

			foreach (byte b in bytes)
			{
				hexString.Append(string.Format("{0:X2}", b));
			}

			return hexString.ToString();
		}

		#endregion
	}
}
